package no.rodland.acc.db;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @Since: Aug 2, 2010 11:27:18 AM
 * @Author: fmr
 */
public class DbUtil {
    private static DbRowComparator ascendingComparator = new DbRowComparator(true);

    public static <T extends DbRow> DateTime getFirstDate(List<T> rows) {
        if (rows == null || rows.size() == 0) {
            return null;
        }
        Collections.sort(rows, ascendingComparator);
        return rows.get(0).getDate();
    }

    public static <T extends DbRow> DateTime getLastDate(List<T> rows) {
        if (rows == null || rows.size() == 0) {
            return null;
        }
        Collections.sort(rows);
        return rows.get(0).getDate();
    }

    public static <T extends DbRow> Map<Integer, T> toMap(List<T> list) {
        Map<Integer, T> map = new HashMap<Integer, T>();
        for (DbRow dbRow : list) {
            //noinspection unchecked
            map.put(dbRow.getId(), (T) dbRow);
        }
        return map;
    }

    public static String getSqlDate(DateTime date) {
        DateTimeFormatter dbDateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
        if (date == null) {
            return null;
        }
        return dbDateFormatter.print(date);
    }
}
